package com.UU.J2EE.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.UU.J2EE.PizzaStore.beans.CustomerBean;
import com.UU.J2EE.PizzaStore.dao.CustomerDao;

public class RegisterServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String username = request.getParameter("Username");
		String password = request.getParameter("Password");
		String email = request.getParameter("Email");
		String phone = request.getParameter("Phone");
		String address = request.getParameter("Address");
		CustomerBean customerBean = new CustomerBean();
		CustomerDao customerDao = new CustomerDao();
		
		customerBean.setName(username);
		//test duplicate username
		if(customerDao.testCustomer(customerBean))
		{
			request.setAttribute("error", "The username has been taken");
			request.getRequestDispatcher("register.jsp").forward(request, response);
			return;
		}
		customerBean.setPassword(password);
		customerBean.setEmail(email);
		customerBean.setPhone(phone);
		customerBean.setAddress(address);
		
		try {
			customerDao.Register(customerBean);
			out.print("<center>Succeed!</center><br>");
			out.print("<center>Please wait for 5 seconds and it will turn to login page automatically...</center><br><br>");
			out.print("<center>Click <a href=login.jsp><u>HERE</u></a> to login directly...</center><br>");
			response.setHeader("REFRESH","5;login.jsp");
			//response.sendRedirect("pizzastore.jsp?Username="+customerBean.getName());
		} catch (Exception e) {
			// TODO: handle exception
			out.print("Error");
		}
		
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
